JBIStream=java.io.BufferedInputStream
module HttpHandler
  include_all(%w(httpclient httpclient.methods httpclient.cookie) , 'org.apache.commons')
  
  # lazy initialized http client (called just when used and only a single one will be created)
  def http_client
    @http_client ||= HttpClient.new
    @http_client.state ||= HttpState.new
    @http_client.getParams().setCookiePolicy('netscape')
    @http_client    
  end
  
  def call_http(method)
    http_code=http_client.executeMethod(method)
    result=read_body_as_stream(method)
    method.releaseConnection()
    [result,http_code]
  end

  
  private 
  def read_body_as_stream(method)
    bis = JBIStream.new( method.responseBodyAsStream())
    res = ''
    bytes=Java::byte[8192].new
    count = bis.read( bytes )
    while( count != -1)
      res << String.from_java_bytes(bytes)[0,count]
      count = bis.read(bytes);
    end
    bis.close()
    res.to_s
  end
end
